package com.andy.nature.utils

import android.content.Context
import android.graphics.Bitmap
import android.media.MediaScannerConnection
import android.os.Environment
import java.io.File
import java.io.FileOutputStream


/**
 * Author:Andy
 * Date:2023/4/28 16:32
 * Description:ImageUtils
 */
object ImageUtils {
    /**
     * 保存图片到相册中
     */
    fun saveImageToGallery(context: Context, bitmap: Bitmap?, name: String? = null): String? {
        try {
            if (bitmap == null) {
                return null
            }
            val f = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).absoluteFile
            if (!f.exists()) {
                f.mkdirs()
            }
            val fileName = name ?: "share.jpg"
            val file = File(f, fileName)
            if (file.exists()) {
                return file.path
            }
            val fos = FileOutputStream(file)
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
            fos.flush()
            fos.close() //通知图库更新，必须添加，否则相册无法更新新添加的图片
            MediaScannerConnection.scanFile(context, arrayOf(file.toString()), null, null)
            return file.path
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }
    }

}